<template>
    <a-modal
      :bodyStyle="bodyStyle"
      :title="title"
      :visible="visible"
      :confirmLoading="confirmLoading"
      :destroyOnClose="true"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form layout='vertical' :form="form">
        <a-form-item>
          <a-input
            v-decorator="[
              'title',
              {
                rules: [{ required: true, message: '请输入标题!' }],
              }
            ]"
            placeholder="请输入标题"
          />
        </a-form-item>
        <a-form-item>
          <a-textarea
            v-decorator="[
              'textContent',
              {
                rules: [{ required: true, message: '请输入文本内容!' }],
              }
            ]"
            placeholder="请输入文本内容"
          />
        </a-form-item>
        <a-form-item>
          <a-upload
              listType="picture-card"
              class="avatar-uploader"
              :showUploadList="false"
              :beforeUpload="beforeUpload"
              v-decorator="['imageFile',{}]"
            >
              <img v-if="imageUrl" :src="imageUrl" alt="avatar"/>
              <div v-else>
                  <a-icon :type="loading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">Upload</div>
              </div>
            </a-upload>
        </a-form-item>
        <a-form-item class="form-item-hidden">
          <a-input type="hidden" v-decorator="['id', {}]"/>
          <!-- <a-input type="hidden" v-decorator="['messageType', {}]"/> -->
        </a-form-item>
      </a-form>
    </a-modal>
</template>
<script>
import api from '@/core/Api'
import serv from './MessageService'
import imageCompress from '@/common/mixins/ImageCompress.js'
import Vue from 'vue'
import { Form, Upload, Button, Input, Modal } from 'ant-design-vue'
Vue.component(Form.name, Form)
Vue.component(Form.Item.name, Form.Item)
Vue.component(Upload.name, Upload)
Vue.component(Button.name, Button)
Vue.component(Input.name, Input)
Vue.component(Input.TextArea.name, Input.TextArea)
Vue.component(Modal.name, Modal)
export default {
  mixins: [imageCompress],
  beforeCreate () {
    this.form = this.$form.createForm(this)
  },
  created () {
    this.productTypes = this.dictionary().PRODUCT_TYPE
  },
  data () {
    return {
      bodyStyle: { height: 400 },
      productTypes: [],
      loading: false,
      imageUrl: '',
      confirmLoading: false
    }
  },
  props: {
    title: {
      type: String,
      required: true
    },
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  watch: {
    visible: function (nvalue) {
      if (nvalue && Object.keys(this.data).length > 0) {
        setTimeout(() => {
          this.form.setFieldsValue(this.data)
        }, 10)
        this.imageUrl = this.data.imageContent
      } else {
        this.imageUrl = ''
      }
    }
  },
  methods: {
    handleOk (e) {
      this.form.validateFields(async (err, values) => {
        if (err) {
          return
        }
        this.confirmLoading = true
        if (values.imageFile) {
          // 验证上传图的是否合规
          if (!this.checkUpload(values.imageFile.file)) {
            this.confirmLoading = false
            return
          }
          const url = await api.readAsDataURL(values.imageFile.file)
          values.imageFile = await this.imgCompressAsFile(url, values.imageFile.file)
        }
        let formData = new FormData()
        for (let key in values) {
          let value = values[key]
          if (value) formData.append(key, value.file ? value.file : value)
        }
        serv.save(formData).then(res => {
          this.confirmLoading = false
          if (res.data.code === 0) {
            this.form.resetFields()
            this.$emit('ok', formData.get('id'))
          } else {
            this.$message.error(res.data.msg)
          }
        })
      })
    },
    handleCancel (e) {
      this.$emit('cancel')
    },
    onChange (value) {
      console.log(value)
      this.classifyIds = value
    },
    onChangeOnlySearch (e) {
      this.onlySearch = e.target.checked
    },
    beforeUpload (file) {
      if (this.checkUpload(file)) {
        api.readAsDataURL(file).then(url => {
          this.imageUrl = url
          this.loading = false
        })
      }
      return false
    },
    checkUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJPG) {
        this.$message.error('只能上传JPG或PNG文件!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图不能大于 2MB!')
      }
      return isJPG && isLt2M
    },
    onChangeUrl (e) {
      console.log(11212)
    },
    onSelect (selectedKeys, info) {
      console.log('selected', selectedKeys, info)
    },
    onCheck (checkedKeys, info) {
      console.log('onCheck', checkedKeys, info)
    }
  }
}
</script>

<style scoped>
img {
  max-width: 100%;
}
</style>
